#include "display.hpp"
#include <Ticker.h>

const static uint8_t num1[] = {0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f};
const static int dppin = 14;
const static int pin[7] = {12, 18, 32, 33, 25, 26, 27};
const static int com[4] = {15, 2, 4, 5};


//const static int dppin = 18;
//const static int pin[7] = {13, 18, 14, 27, 26, 25, 33};
//const static int com[4] = {15, 2, 4, 5};

int showstate = 1;

static int bright = 127; //亮度

static int dlsplayShowNum = 0;

void displayPinInit()
{
    pinMode(34,INPUT);
    pinMode(35,INPUT);
    for (int i = 0; i < 7; i++)
    {
        pinMode(pin[i], OUTPUT);
        digitalWrite(pin[i], HIGH);
    }

    pinMode(dppin, OUTPUT);
    digitalWrite(dppin, LOW);

    //com端口pwm初始化
    for (int i = 0; i < 4; i++)
    {
        pinMode(com[i], OUTPUT);
        digitalWrite(com[i], LOW);
        /*ledcSetup(i, 1000 ,8);//通道i，频率1000hz，8位分辨率
        ledcAttachPin(com[i], i);
        ledcWrite(i,127);*/
    }
    showstate = 1;
}

void displaySetData(int dat)
{
    dat %= 10;
    for (int i = 0; i < 7; i++)
    {
        digitalWrite(pin[i], (num1[dat] >> i) & 0x01);
    }
}
void displayClear()
{
    for (int i = 0; i < 4; i++)
    {
        digitalWrite(com[i], HIGH);
    }
}

void displaySeleteCom(int comn)
{
    comn %= 4;
    for (int i = 0; i < 4; i++)
    {
        digitalWrite(com[i], HIGH);
        //ledcWrite(i, 255);
    }

    digitalWrite(com[comn], LOW);
    //ledcWrite(comn, bright);
}

void displayShowTimerCallback()
{
    static int i = 0;
    static int dataShow = dlsplayShowNum;

    displaySeleteCom(3 - i);
    //displayClear();
    displaySetData(dataShow % 10);

    dataShow /= 10;
    (++i) > 3 ? (i = 0, dataShow = dlsplayShowNum) : NULL;
}

Ticker tickerDisplay;
Ticker turnDp;
void displayShowTimerInit()
{
    tickerDisplay.attach_ms(1, displayShowTimerCallback);
    turnDp.attach_ms(1000, [&]()
                     { digitalWrite(dppin, !digitalRead(dppin)); });
}

void displayInit()
{
    displayPinInit();
    displayShowTimerInit();
}

void displaySetShowNum(int dat)
{
    dlsplayShowNum = dat;
}

void displayState(int state)
{
    showstate = state;
    if (state == 0)
    {
        tickerDisplay.detach();
        turnDp.detach();
        displayClear();
        digitalWrite(dppin, 0);
        
    }
    else
    {
        tickerDisplay.attach_ms(1, displayShowTimerCallback);
        turnDp.attach_ms(1000, [&]()
                         { digitalWrite(dppin, !digitalRead(dppin)); });
    }
}
